//
//  UIView+Xib.swift
//  weibo
//
//  Created by 阿城 on 15/12/5.
//  Copyright © 2015年 阿城. All rights reserved.
//

import UIKit

let kSwitchVcNotifcation = "kSwitchVcNotifcation"
let kScreenWidth = UIScreen.mainScreen().bounds.width
let kScreenHeight = UIScreen.mainScreen().bounds.height
let kMargin: CGFloat = 10
let kStatusFont: CGFloat = 15

// 自定义的log
// 在 BuildSettting 中 搜索 other swift flags 添加一个 `-D DEBUG`
func printLog<T>(
    message: T,
    file: String = __FILE__,
    line: Int = __LINE__,
    method: String = __FUNCTION__
    ){
        #if DEBUG
            print("\((file as NSString).lastPathComponent)[\(line)]\(method):\(message)")
        #endif
}


// MARK: - Xib
extension UIView{

    @IBInspectable var cornerRadius: CGFloat {
        get{
            return self.layer.cornerRadius
        }
        set{
            self.layer.cornerRadius = newValue
            self.layer.masksToBounds = true
        }
    }
    
    @IBInspectable var borderWidth: CGFloat{
        get{
            return self.layer.borderWidth
        }
        set{
            self.layer.borderWidth = newValue
        }
    }
    
}

//MARK: - BarButtonItem
extension UIBarButtonItem{
    
    convenience init(imgName: String? = nil, title: String? = nil, target: AnyObject?, action: Selector?){
        
        let barBtn = UIButton()
        barBtn.addTarget(target, action: action!, forControlEvents: .TouchUpInside)
        
        if let name = imgName {
        
            barBtn.setImage(UIImage(named: name), forState: .Normal)
            barBtn.setImage(UIImage(named: "\(name)_highlighted"), forState: .Highlighted)
        }
        if let text = title {
            
            barBtn.setTitle(text, forState: .Normal)
            barBtn.setTitleColor(UIColor.blackColor(), forState: .Normal)
            barBtn.setTitleColor(UIColor.orangeColor(), forState: .Highlighted)
            barBtn.titleLabel?.font = UIFont.systemFontOfSize(15)
        }
  
        self.init()
        barBtn.sizeToFit()
        customView = barBtn

    }
    
}

//MARK: - Color
class SCColor {
    class func getColor(R: CGFloat, G: CGFloat, B: CGFloat) -> UIColor {
        return UIColor(red: R/255, green: G/255, blue: B/255, alpha: 1)
    }
    
    class func getRadomColor() -> UIColor {
        return SCColor.getColor(CGFloat(arc4random() % 255), G: CGFloat(arc4random() % 255) , B: CGFloat(arc4random() % 255) )
    }
}

//MARK: - label
extension UILabel{
    /**
     UIlabel遍历构造函数
     
     - parameter titleText: 文本内容
     - parameter color:     文本颜色
     - parameter fontSize:  字体大小
     
     - returns: UILabel
     */
    convenience init(titleText: String, color: UIColor = UIColor.blackColor(), fontSize: CGFloat) {
        self.init()
        text = titleText
        font = UIFont.systemFontOfSize(fontSize)
        textColor = color
    }
    
}

//MARK: - Button
extension UIButton{
    convenience init(imageName: String, title: String) {
        self.init()
        setBackgroundImage(UIImage(named: "timeline_card_bottom_background_highlighted"), forState: UIControlState.Highlighted)
        setBackgroundImage(UIImage(named: "timeline_card_bottom_background"), forState: UIControlState.Normal)
        setImage(UIImage(named: imageName), forState: UIControlState.Normal)
        setTitle(title, forState: UIControlState.Normal)
        setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal)
        setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Highlighted)
        titleLabel?.font = UIFont.systemFontOfSize(14)
        titleEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: -5)
    }
}

extension NSDate {
    private class func getDate(dateStr: String)->NSDate{
        //"created_at" = "Wed Dec 09 13:45:02 +0800 2015"
        let dateformat = NSDateFormatter()
        dateformat.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        dateformat.locale = NSLocale(localeIdentifier: "en_US")//???
        return dateformat.dateFromString(dateStr)!
    }
    
    class func sinceString(dateStr: String)->String {
        
        let calendar = NSCalendar.currentCalendar()
        let date = getDate(dateStr)
        
        if calendar.isDateInToday(date){
            //今天
            let timeInterval:Int = Int(-date.timeIntervalSinceNow)
//            printLog(timeInterval)
            
            if timeInterval < 60 {
                return "刚刚"
            }else if timeInterval < 60 * 60 {
                return "\(timeInterval / 60)分钟前"
            }else {
                return "\(timeInterval / 60 / 60)小时前"
            }
            
            
        }else if calendar.isDateInYesterday(date){
            //昨天
            let mat = NSDateFormatter()
            mat.dateFormat = "HH:mm"
            return mat.stringFromDate(date)
            
        }else{
            let mat = NSDateFormatter()
            mat.dateFormat = "yyyy"
            let creatTime = mat.stringFromDate(date)
            let currentTime = mat.stringFromDate(NSDate())
            if creatTime == currentTime{
                //同一年
                mat.dateFormat = "MM-dd HH:mm:ss"
                return mat.stringFromDate(date)
            }else{
                //不同年
                mat.dateFormat = "yyyy-MM-dd HH:mm:ss"
                return mat.stringFromDate(date)
            }
        }   
    }
    
}


// MARK: - 图片
extension UIImage{
    
    /// 缩放图片
    ///
    /// - parameter scale: 缩放比例
    func scaleImage(scale: CGFloat) -> UIImage {
        //计算size
        let newSize = CGSize(width: scale * size.width, height: scale * size.height)
        //开启图片上下文
        UIGraphicsBeginImageContext(newSize)
        //绘图
        drawInRect(CGRect(origin: CGPointZero, size: newSize))
        //取图
        let img = UIGraphicsGetImageFromCurrentImageContext()
        //关闭图片上下文
        UIGraphicsEndImageContext()
        
        return img
    }
    
    /// 屏幕截图
    class func shotScreen() -> UIImage {
    
        // 获取window
        let window = UIApplication.sharedApplication().keyWindow!
        // 开始上下文
        UIGraphicsBeginImageContext(window.bounds.size)
        // 绘制
        window.drawViewHierarchyInRect(window.bounds, afterScreenUpdates: false)
        // 截取
        let img = UIGraphicsGetImageFromCurrentImageContext()
        // 关闭上下文
        UIGraphicsEndImageContext()
        
        return img
    }
    
    /// 获取启动图
    class func getLaunchImage() -> UIImage? {
        
        //读取info
        let userInfo = NSBundle.mainBundle().infoDictionary
        let launchImages = userInfo!["UILaunchImages"] as! [[String: AnyObject]]
        //获取屏幕大小
        let screenSize = UIScreen.mainScreen().bounds.size
        //获取iOS的版本号
        let version = UIDevice().systemVersion
        
        //遍历图片信息
        for imageInfo in launchImages {
            //最小版本号
            let miniVersion = imageInfo["UILaunchImageMinimumOSVersion"] as! String
            //启动图的大小
            let imageSize = CGSizeFromString(imageInfo["UILaunchImageSize"] as! String)
            //版本对比
            let versionResult = (version as NSString).compare(miniVersion) != NSComparisonResult.OrderedAscending
            //大小对比
            let sizeResult = CGSizeEqualToSize(imageSize, screenSize)
            
            //找到对应启动图
            if versionResult && sizeResult {
                let name = imageInfo["UILaunchImageName"] as! String
                return UIImage(named: name)
            }
        }
        return nil
    }
}


extension UIView{
    
    var x: CGFloat{
        get{
            return frame.origin.x
        }
        set{
            frame.origin.x = newValue
        }
    }
    
    var y: CGFloat{
        get{
            return frame.origin.y
        }
        set{
            frame.origin.y = newValue
        }
    }
    
    var width: CGFloat{
        get{
            return frame.size.width
        }
        set{
            frame.size.width = newValue
        }
    }
    
    var height: CGFloat{
        get{
            return frame.size.height
        }
        
        set{
            frame.size.height = newValue
        }
    }
    
}

